package com.kaifamiao.kfm.config.filter;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kaifamiao.kfm.entity.SysUser;
import com.kaifamiao.kfm.util.Constants;
import com.kaifamiao.kfm.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 验证码校验
 */
@Component
public class CaptchaFilter extends OncePerRequestFilter {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        HttpSession session = request.getSession();
        // 能取到 code 参数，说明是登录请求
        String code = request.getParameter("code");
        if (code != null){
            // 登录
            String captcha = (String) redisTemplate.opsForValue().get(session.getId() + Constants.CAPTCHA_KEY_SUFF);
            if (code.equalsIgnoreCase(captcha)){
                redisTemplate.delete(session.getId() + Constants.CAPTCHA_KEY_SUFF);
                filterChain.doFilter(request, response);
            }else{
                response.setContentType("text/json;charset=utf-8");
                response.getWriter().write(JSON.toJSONString(JsonResult.error( "验证码错误")));
            }
        } else{
            filterChain.doFilter(request, response);
        }
    }
}
